﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Util;
using System.Configuration;
using DSAServer.Models.Output;
using Top.Api.Domain;
using System.Text.RegularExpressions;
using DSAServer.Utils;

namespace DSAServer.Service
{
    public class TopService
    {
        public TaobaoOrderInfo GetTopOrder(string oid)
        {
            TaobaoOrderInfo result = new TaobaoOrderInfo();
            //正式环境需要设置为,http://gw.api.taobao.com/router/rest
            string url = "http://gw.api.taobao.com/router/rest";
            ManagerService ms = new ManagerService();
            string appkey = ms.GetConfigItem("client_id").data.cvalue;// ConfigurationManager.AppSettings["appkey"];//23096987
            string appsecret = ms.GetConfigItem("client_secret").data.cvalue; //ConfigurationManager.AppSettings["appsecret"];
            string sessionkey = ms.GetConfigItem("client_token").data.cvalue;// ConfigurationManager.AppSettings["sessionkey"];   //如沙箱测试帐号sandbox_c_1授权后得到的sessionkey
            try
            {
                ITopClient client = new DefaultTopClient(url, appkey, appsecret);
                TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
                req.Fields = "seller_nick, buyer_nick, title, type, created, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, num_iid, num, price, cod_fee, cod_status, shipping_type, is_daixiao,consign_interval,arrive_interval,arrive_cut_time,orders,receiver_mobile,receiver_address,receiver_name,receiver_state,receiver_city";
                //req.Fields = "seller_nick, buyer_nick, title, type, created, tid, seller_rate,buyer_flag, buyer_rate, status,show_ext,payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no,alipay_id,buyer_message, pic_path, num_iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,buyer_email,buyer_area, trade_from,is_lgtype,is_force_wlb,is_brand_sale,buyer_cod_fee,discount_fee,seller_cod_fee,express_agency_fee,invoice_name,service_orders,credit_cardfee,step_trade_status,step_paid_fee,mark_desc,has_yfx,yfx_fee,yfx_id,yfx_type,trade_source,orders";
                req.Tid = long.Parse(oid);
                TradeFullinfoGetResponse response = client.Execute(req, sessionkey);
                LogUtil.Info("error info:" + response.ErrMsg + "|" + response.SubErrMsg);
                if (!response.IsError)
                {
                    LogUtil.Info(DateTime.Now + ":淘宝API获取成功");
                    //判断订单状态,已付款的进行读取
                    //if (response.Trade.Status == OrderStatus.WAIT_SELLER_SEND_GOODS.ToString())
                    //{
                    result.buyermessage = response.Trade.BuyerMessage ?? "";
                    result.buyernick = response.Trade.BuyerNick;
                    result.no = oid;
                    result.num = response.Trade.Num.ToString();
                    result.receiveraddress = response.Trade.ReceiverAddress;
                    result.receivermobile = response.Trade.ReceiverMobile;
                    result.receivername = response.Trade.ReceiverName;
                    result.status = response.Trade.Status;
                    result.totalfee = response.Trade.TotalFee;
                    result.created = Convert.ToDateTime(response.Trade.Created);
                    result.orders = new List<TaobaoSunOrderInfo>();
                    foreach (Order order in response.Trade.Orders)
                    {
                        if (CheckPic(order.Title))
                        {
                            string strNum = RegexNum(order.Title);
                            result.orders.Add(new TaobaoSunOrderInfo
                            {
                                no = oid,
                                oid = order.Oid.ToString(),
                                num = strNum != "" ? (Int32.Parse(strNum.Replace("张", "")) * order.Num).ToString() : order.Num.ToString(),
                                payment = order.Payment,
                                skupropertiesname = RegexSku(order.SkuPropertiesName ?? "", "尺寸"),// RegexSku(order.SkuPropertiesName ?? ""),
                                status = order.Status,
                                title = order.Title,
                                producttype = RegexProductType(order.Title),
                                picpaper = RegexSku(order.SkuPropertiesName ?? "", "相纸")
                            });
                        }
                    }
                    //}
                    //else
                    //{
                    //    result = null;
                    //    LogUtil.Info("error info:买家还没有付款" + response.SubErrMsg);
                    //}
                    //LogUtil.Info(DateTime.Now + ":淘宝接口返回数据：" + JsonHelper.SerializeObject(result));
                }
                else
                {
                    LogUtil.Info("error info:" + response.ErrMsg + "|" + response.SubErrMsg);
                }
            }
            catch (Exception ex)
            {
                result = null;
                LogUtil.Info("error info:" + ex.Message);
            }
            return result;
        }

        private string RegexProductType(string title)
        {
            string result = "";
            if (title.Substring(0, 3) == "洗照片")
                result = "普通照片";
            else if (title.Substring(0, 3) == "拍立得")
                result = "拍立得";
            else if (title.Substring(0, 3) == "正方形")
                result = "正方形";
            return result;
        }

        public bool CheckPic(string title)
        {
            bool result = false;
            if (title.Substring(0, 3) == "洗照片" || title.Substring(0, 3) == "拍立得" || title.Substring(0, 3) == "正方形")
                result = true;
            return result;
        }

        public string RegexSku(string str)
        {
            Regex reg = new Regex(@"\d*(\d寸)");
            return reg.Match(str).Value;
        }

        public string RegexNum(string str)
        {
            Regex reg = new Regex(@"\d*(\d张)");
            return reg.Match(str).Value;
        }

        public string RegexSku(string str, string skuname)
        {
            //Regex reg = new Regex(@"\d*(\d寸)");
            //return reg.Match(str).Value;
            string result = "";
            try
            {
                string[] skuList = str.Split(new char[] { ';' });
                foreach (string sku in skuList)
                {
                    string[] temp = sku.Split(new char[] { ':' });
                    if (temp[0] == skuname)
                        result = temp[1];
                }
            }
            catch { }
            return result;
        }

        public string GetCode()
        {
            return "";
        }

        public string GetSessionKey()
        {
            string url = "https://oauth.taobao.com/token";
            Dictionary<string, string> props = new Dictionary<string, string>();
            props.Add("grant_type", "authorization_code");
            props.Add("code", "LQyDxLEpCH4fGeD6HSCuik7w254887");
            props.Add("client_id", "23096885");
            props.Add("client_secret", "2450de9a4d7b29e60a8cbb43c0f83553");
            props.Add("redirect_uri", "http://www.guanjienet.com");
            props.Add("view", "web");
            string s = "";
            try
            {
                WebUtils webUtils = new WebUtils();
                s = webUtils.DoPost(url, props);
            }
            catch (Exception e)
            { }
            return s;
        }
    }
}